<template>
    <div class="payment">
        <div class="content">
            <div class="item">
                <van-cell title="订单编号" :value="payOrder.order_code" />
                <van-cell title="订单金额" :value="(Number(payOrder.subtotal)+15)+'元'" />
            </div>
            <div class="item">
                <van-cell @click="beforePay" icon="wechat" title="微信支付" label="微信安全支付" />
                <van-cell @click="balancePay" v-if="this.userState == 2" icon="shop-o" title="余额支付" label="当前余额" :value="balance" />
            </div>
        </div>
        <van-tabbar route active-color="#ee0a24">
            <van-tabbar-item to="/" icon="shop-o">首页</van-tabbar-item>
            <van-tabbar-item to="/goodstypelist" icon="apps-o">全部分类</van-tabbar-item>
            <van-tabbar-item to="/shopcart" icon="shopping-cart-o">购物车</van-tabbar-item>
            <van-tabbar-item to="/center" icon="manager-o">会员中心</van-tabbar-item>
        </van-tabbar>
    </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
    data(){
        return{
            balance:0,//余额
        }
    },
    computed: {
        ...mapState(['openid', 'payOrder', 'userState'])
    },
    mounted(){
        console.log(this.payOrder,this.userState)
        if (this.userState == 2) {
            this._getBalance()
        }
    },
    methods:{
        async beforePay() {
            console.log('点击微信支付')
            let formData = new FormData()
            formData.append('uid', this.payOrder.uid)
            formData.append('oid', this.payOrder.id)
            formData.append('totalFee', Number(this.payOrder.subtotal)+15)
            formData.append('orderName', 'WowSurprise有惊喜')
            formData.append('openid', this.openid)
            formData.append('outTradeNo', this.payOrder.order_code)
            let { data: { code, data } } = await this.$http.post(this.$api.wechatPay,formData)
            if(code === 0) {
                this.$toast.loading({
                    message: 'Loading...',
                    forbidClick: true,
                    loadingType: 'spinner',
                    duration: 0
                })
                this.Pay(data.package)
            }
        },
        Pay (data) {
            let vm = this
            if (typeof WeixinJSBridge === 'undefined') {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', vm.onBridgeReady(data), false)
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', vm.onBridgeReady(data))
                    document.attachEvent('onWeixinJSBridgeReady', vm.onBridgeReady(data))
                }
            } else {
                vm.onBridgeReady(data)
            }
        },
        onBridgeReady (data) {
            this.$toast.clear()
            let self = this
            /* eslint-disable */
            WeixinJSBridge.invoke(
                'getBrandWCPayRequest', {
                    'appId': data.appId,
                    'timeStamp': String(data.timeStamp),    //这里必须要转换为字符串。ios跟android表现不同。后台返回的是数值，但是微信方面必须要json参数都是字符串形式，android会自动转换成字符串（当时我在这里也找了很久的博文才知道的）
                    'nonceStr': data.nonceStr,
                    'package': data.package,
                    'signType': data.signType,
                    'paySign': data.paySign
                },
                function (res) {
                    if (res.err_msg === 'get_brand_wcpay_request:ok') {
                        // self.$router.replace('/payComplete')
                        window.location.href = 'http://www.youjingxi.net.cn/payComplete'
                    } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
                        self.$toast('支付取消!')
                    } else {
                        self.$toast('支付失败!')
                    }
                }
            )
            /* eslint-enable */
        },
        //获取余额
        async _getBalance() {
            let { data: { code, data } } = await this.$http.get(this.$api.platformBalance,{openid: this.openid})
            if (code === 0) {
                this.balance = data
            } else if(code === 1) {
                this.balance = 0
            }
        },
        //点击余额支付
        balancePay() {
            if (this.balance < this.payOrder.subtotal) {
                this.$toast('余额不足')
                return
            }
            this.$confirm('使用余额支付？').then(() => {
                this._balancePay()
            })
        },
        //余额支付
        async _balancePay() {
            let form = {
                order_code: this.payOrder.order_code,
                subtotal: Number(this.payOrder.subtotal)+15,
                openid: this.openId
            }
            let { data: { code } } = await this.$http.post(this.$api.platformPay,form)
            if (code === 0) {
                this.$router.push('/payComplete')
            }
        },
    }
}
</script>
<style lang="scss" scoped>
    .payment{
        .content{
            .item{
                padding-bottom: 1rem;
            }
        }
    }
</style>